/**
 * 面试题 04.08. 首个共同祖先
 * https://leetcode-cn.com/problems/first-common-ancestor-lcci/
 */
public class Solutions_mianshi_04_08 {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(5);
        root.left.left = new TreeNode(6);
        root.left.right = new TreeNode(2);
        root.left.right.left = new TreeNode(7);
        root.left.right.right = new TreeNode(4);
        root.right = new TreeNode(1);
        root.right.left = new TreeNode(0);
        root.right.right = new TreeNode(8);

//        TreeNode p = new TreeNode(5);
//        TreeNode q = new TreeNode(1);  // output: 3

        TreeNode p = new TreeNode(5);
        TreeNode q = new TreeNode(4);  // output: 5

        TreeNode result = lowestCommonAncestor(root, p, q);
        System.out.println(result);
    }

    public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || root.val == p.val || root.val == q.val) {
            return root;
        }
        // root 不等于 p 或 q 时，递归左右子树，在左右子树中查找 p 和 q
        TreeNode leftRes = lowestCommonAncestor(root.left, p, q);
        TreeNode rightRes = lowestCommonAncestor(root.right, p, q);
        if (leftRes == null || rightRes == null) {
            // p 和 q 只存在于一侧，且一个节点一定在另一个节点的子树中
            return leftRes == null ? rightRes : leftRes;
        }
        // 分别分布在 root 的左右子树中
        return root;
    }
}
